package com.example.springpostbody.core.filter;

import com.example.springpostbody.core.CustomRequestWrapper;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.Ordered;

import java.io.IOException;
import java.util.Arrays;

/*@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter(urlPatterns = "/*", filterName = "postRequestFilter")*/
public class PostRequestFilter implements Filter
        //, Ordered
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        if(servletRequest instanceof CustomRequestWrapper){
            HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
            System.out.println("低级 PostRequestFilter --> 是自定义CustomRequestWrapper");
            if(Arrays.asList("POST", "PUT").contains(httpRequest.getMethod())) {
                // 设置自定义的ServletRequest
                CustomRequestWrapper requestWrapper = new CustomRequestWrapper(httpRequest);

                System.out.println("低级 PostRequestFilter --> 获取报文数据="+requestWrapper.getBody());
                filterChain.doFilter(requestWrapper, servletResponse);
            }
        }else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    /*@Override
    public int getOrder() {
        return 0;
    }*/
}
